<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/12
 * Time: 16:12
 * * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */
namespace app\admin\controller;

use app\common\model\AmountLog;
use app\common\model\CheckUser;
use app\common\model\FollowUser;
use app\common\model\UserCommission;
use app\common\model\UserMessage;
use app\Request;
use app\services\wechat\Miniprogram;
use dh2y\qrcode\QRcode;

class  User{
    public  function  userList(Request $request){
        $param = $request->param();
        $userModel = new \app\common\model\User();
        $limit = 10;
        $start = 0;
        $QRcode = new QRcode();
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['status', 'in', [1, 0]];
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['phone|nickname', 'like', '%' . $param['name'] . '%'];
        }
        if (isset($param['level_id']) && !empty($param['level_id'])) {
            $where[] = ['level_id', '=', $param['level_id']];
        }
        if (isset($param['login_ip']) && !empty($param['login_ip'])) {
            $where[] = ['last_login_ip', '=', $param['login_ip']];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])){
            $where[] = ['create_time','>=',strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])){
            $where[] = ['create_time','<=',strtotime($param['end_time'])];
        }
        $field = 'id';
        $order = 'desc';
        if (isset($param['field']) && !empty($param['field'])){
            $field = $param['field'];
        }
        $userList = $userModel
            ->where($where)
            ->order($field,$order)
            ->limit($start, $limit)->select()->toArray();
        $count = $userModel->where($where)->count();
        $pidArray = array_column($userList, 'pid');
        $pUserList = $userModel
            ->where('id','in',$pidArray)
            ->field('id,phone,nickname,avatar')->select() ->toArray();
        $pUserListById = [];
        if ($pUserList){
            $pUserListById = array_column($pUserList,null,'id');
        }
        $pay_type = \app\common\model\Config::getConfigValue('pay_type');
        $appid = '';
        if ($pay_type == 1){
            $appid = \app\common\model\Config::getConfigValue('xcx_appid');
        }else{
            $appid = \app\common\model\Config::getConfigValue('m_xcx_appid');
        }
       $Miniprogram =  new Miniprogram();
        foreach ($userList as $key => $value) {
            if ($value['sex'] == 1){
                $userList[$key]['sex_name'] = '男';
            }else{
                $userList[$key]['sex_name'] = '女';
            }
            if (array_key_exists($value['pid'], $pUserListById)) {
                $userList[$key]['p_phone'] = $pUserListById[$value['pid']]['phone'];
                $userList[$key]['p_nickname'] = $pUserListById[$value['pid']]['nickname'];
                $userList[$key]['p_avatar'] = $pUserListById[$value['pid']]['avatar'];
            } else {
                $userList[$key]['p_phone'] = '';
                $userList[$key]['p_nickname'] ='';
                $userList[$key]['p_avatar'] = '';
            }
            $url = getProtocol() . $_SERVER["HTTP_HOST"].'/H5/index.html?invite='.$value['invite_code'].'#/';
            $imageString = $QRcode->png($url, './uploads/qrcode/'.$value['invite_code'].'.png', "2", 4, 1)->entry();
            $userList[$key]['invite_url'] = $imageString;
            if ($appid){
                $userList[$key]['invite_xcx_url'] = $Miniprogram->getwxacode($value['invite_code']);
            }else{
                $userList[$key]['invite_xcx_url'] = '';
            }

        }

        return success('用户列表', ['list' => $userList, 'count' => $count]);
    }

    public function updateStatus(Request $request){
        $param = $request->param();
        $staffModel = new \app\common\model\User();
        $staffModel->where(['id' => $param['id']])->update(['status'=> $param['status']]);
        return success('操作成功');
    }
    public function userInfo(Request $request){
        $param = $request->param();
        $userModel = new \app\common\model\User();
        $userInfo = $userModel->where(['id' => $param['uid']])->find();
        return success('用户信息',$userInfo) ;

    }

    public function setTopUser(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\common\model\User();
        $topUser = $userModel->where(['id' => $param['top_id']])->find();
        $userModel->where(['id' => $param['id']])
            ->update(['pid' => $param['top_id'], 'pids' => $topUser['pids'] . ',' . $param['top_id']]);
        return success('修改成功');
    }

    public function authentication(Request $request){
        $param = $request->param();
        $staffModel = new \app\common\model\User();
        $data['is_authentication'] = $param['is_authentication'];
        if (isset($param['remark']) && !empty($param['remark'])){
            $data['remark'] = $param['remark'];
        }
        $staffModel->where(['id' => $param['id']])->update($data);
        return success('操作成功');
    }
    public function distributionLog(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['uc.create_time','>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['uc.create_time','<=',strtotime($param['end_time'])];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['u.nickname','like', '%'.$param['name'].'%'];
        }
        if (isset($param['receive_name']) && !empty($param['receive_name'])) {
            $where[] = ['ru.nickname','like', '%'.$param['receive_name'].'%'];
        }
        if (isset($param['receive_uid']) && !empty($param['receive_uid'])) {
            $where[] = ['uc.receive_uid','=', $param['receive_uid']];
        }
        $userCommissionModel  = new UserCommission();
        $list = $userCommissionModel->alias('uc')
            ->leftJoin('user u','uc.trigger_uid = u.id')
            ->leftJoin('user ru','uc.receive_uid = ru.id')
            ->where($where)
            ->limit($start,$limit)
            ->field('uc.*,u.nickname,u.phone,u.avatar ,ru.nickname as ru_nickname,ru.phone as ru_phone,ru.avatar as ru_avatar')
            ->select()->toArray();
        $count = $userCommissionModel->alias('uc')
            ->leftJoin('user u','uc.trigger_uid = u.id')
            ->leftJoin('user ru','uc.receive_uid = ru.id')
            ->where($where)
            ->limit($start,$limit)
            ->field('uc.*,u.nickname,u.phone,u.avatar')
            ->count();
        return success('分销列表',['list' => $list,'count' => $count]);
    }

    public function amountLog(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['a.create_time','>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['a.create_time','<=',strtotime($param['end_time'])];
        }
        if (isset($param['amount_type']) && !empty($param['amount_type'])) {
            $where[] = ['amount_type','=',strtotime($param['amount_type'])];
        }
        if (isset($param['operation_source']) && !empty($param['operation_source'])) {
            $where[] = ['operation_source','=',strtotime($param['operation_source'])];
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['uid','=',$param['uid']];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['nickname|phone','like','%'.$param['name'].'%'];
        }
        $amountModel   = new AmountLog();
        $list = $amountModel->alias('a')
            ->leftJoin('user u','a.uid = u.id')
            ->field('a.*,u.nickname,u.phone,u.avatar')
            ->where($where)
            ->limit($start,$limit)
            ->order('create_time','desc')
            ->select()->toArray();
        $amountModel->getLastSql();
        $count = $amountModel
            ->alias('a')
            ->leftJoin('user u','a.uid = u.id')
            ->where($where)
            ->limit($start,$limit)
            ->field('a.*,u.nickname,u.phone,u.avatar')
            ->count();
        return success('账变',['list' => $list,'count' => $count]);
    }

    public function FollowUser(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        $where = [];
        if ( isset($param['uid']) && !empty($param['uid'])){
            $where[] = ['uid' => $param['uid']];
        }
        if ( isset($param['follow_uid']) && !empty($param['follow_uid'])){
            $where [] = ['follow_uid' => $param['follow_uid']];
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $followUser = new FollowUser();
        $list = $followUser->alias('fu')
            ->where($where)
            ->leftJoin('user u','fu.follow_uid = u.id')
            ->leftJoin('user uf','fu.follow_uid = uf.id')
            ->limit($start,$limit)
            ->field('u.nickname,u.avatar,fu.create_time,uf.nickname as uf_nickname,uf.avatar as uf_acatar')
            ->select()->toArray();
        $count = $followUser->alias('fu')
            ->where($where)
            ->leftJoin('user u','fu.follow_uid = u.id')
            ->leftJoin('user uf','fu.follow_uid = uf.id')
            ->count();
        return success('关注',['list' => $list,'count' => $count]);
    }

    public function setAmount(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\common\model\User();
        $userInfo  = $userModel->where(['id' => $param['id']])->find();
        if ($param['type'] == 1) {
            if (isset($param['balance']) && !empty($param['balance'])) {
                $userModel->where(['id' => $param['id']])->inc('balance', $param['balance'])->update();
                $amountModel = new AmountLog();
                $amountModel->insert([
                    'uid' => $param['id'],
                    'amount' => $param['balance'],
                    'amount_type' =>'1',
                    'operation_source' => 16,
                    'amount_direction' => 1,
                    'create_time' => time(),
                ]);
            }
        } else {
            if (isset($param['balance']) && !empty($param['balance'])) {
                if ($userInfo['balance'] >= $param['balance'] ){
                    $userModel->where(['id' => $param['id']])->dec('balance', $param['balance'])->update();
                    $amountModel = new AmountLog();
                    $amountModel->insert([
                        'uid' => $param['id'],
                        'amount' => $param['balance'],
                        'amount_type' =>'1',
                        'operation_source' => 17,
                        'amount_direction' => 2,
                        'create_time' => time(),

                    ]);
                }else{
                  return  error('余额不足');
                }
            }
        }
        return success('修改成功');
    }

    public function checkUser(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['is_agree']) && !empty($param['is_agree'])) {
            $where[] = ['cu.is_agree','=',$param['is_agree']];
        }

        if (isset($param['check_uid']) && !empty($param['check_uid'])) {
            $where[] = ['cu.check_uid','=',$param['check_uid']];
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['cu.uid','=',$param['uid']];
        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.nickname','like','%'.$param['nickname'].'%'];
        }
        if (isset($param['check_nickname']) && !empty($param['check_nickname'])) {
            $where[] = ['uc.nickname','like','%'.$param['check_nickname'].'%'];
        }
        $checkUserModel = new CheckUser();
        $list = $checkUserModel
            ->alias('cu')
            ->leftJoin('user u', 'cu.check_uid = u.id')
            ->leftJoin('user uc', 'cu.uid = uc.id')
            ->where($where)
            ->limit($start,$limit)
            ->order('cu.create_time','desc')
            ->field('u.nickname,u.phone,uc.nickname as check_nickname,uc.phone as check_phone ,cu.create_time,cu.is_agree,cu.id')
            ->select()->toArray();
        foreach ($list as $key => $value){
            $list[$key]['create_time'] = date('Y-m-d H:i',$value['create_time']);
        }
        $count = $checkUserModel
            ->alias('cu')
            ->leftJoin('user u', 'cu.check_uid = u.id')
            ->leftJoin('user uc', 'cu.uid = uc.id')

            ->where($where)
            ->count();
        return success('申请用户',['list' => $list,'count' => $count]);
    }

    public function agreeCheck(Request $request){
        $param = $request->param();
        $checkUserModel = new CheckUser();
        $checkUserInfo = $checkUserModel->where(['id' => $param['id']])->find();
        if ($checkUserInfo['is_agree'] != 1){
            return error('已处理');
        }
        $checkUserModel->where(['id' => $param['id']])->update(['is_agree' => $param['is_agree']]);
        if ($param['is_agree'] == 2){
            $amountModel = new AmountLog();
            $recharge_ratio = \app\common\model\Config::getConfigValue('recharge_ratio');
            $handling_fees_amount =  bcdiv($checkUserInfo['price'],$recharge_ratio,2);
            $amountModel->where(['correlation_id'=>$param['id'] ,'create_time' => $checkUserInfo['create_time']])->update(['handling_fees' => $checkUserInfo['price'],'handling_fees_amount' =>$handling_fees_amount]);

        }else{
            $userModel = new \app\common\model\User();
            $userModel->where(['id' => $checkUserInfo['uid']])->inc('balance',$checkUserInfo['price'])->update();
            $amountData = [
                'uid' => $checkUserInfo['uid'] ,
                'amount' => $checkUserInfo['price'],
                'amount_type' => 1,
                'operation_source' => 19,
                'amount_direction' => 1,
                'create_time' => time(),
                'correlation_id'  => $param['id'],
                'ratio' => 1,
                'original_price' =>$checkUserInfo['price']
            ];
            $amountModel = new   AmountLog();
            $amountModel->insert($amountData);
        }
        return success('操作成功');

    }

    public function chatLog(Request $request){
        $param = $request->param();
        $userMessageModel = new UserMessage();
        if ( isset($param['receive_uid']) && !empty($param['receive_uid'])){
            $where[] = ['receive_uid','=', $param['receive_uid']];
        }
        if ( isset($param['send_uid']) && !empty($param['send_uid'])){
            $where [] = ['send_uid' ,'=', $param['send_uid']];
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if ( isset($param['send_nickname']) && !empty($param['send_nickname'])){
            $where[] = ['su.nickname','like','%'.$param['send_nickname'].'%'];
        }

        if ( isset($param['receive_nickname']) && !empty($param['receive_nickname'])){
            $where[] = ['ru.nickname','like','%'. $param['receive_nickname'].'%'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $list = $userMessageModel->alias('um')
            ->where($where)
            ->leftJoin('user su','um.send_uid = su.id')
            ->leftJoin('user ru','um.receive_uid = ru.id')
            ->limit($start,$limit)
            ->field('su.nickname as send_nickname,su.avatar as send_avatar,ru.nickname as receive_nickname,ru.avatar as receive_acatar,um*')
            ->order('create_time','desc')
            ->select()
            ->toArray();
        $count = $userMessageModel->alias('fu')
            ->where($where)
            ->leftJoin('user su','um.send_uid = su.id')
            ->leftJoin('user ru','um.receive_uid = ru.id')
            ->count();
        return success('聊天',['list' => $list,'count' => $count]);

    }

}